package com.wk.job.heartbeat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.wk.net.heartbeat.HeartbeatTransferer;

public class JobStateHeartbeatTransferer implements HeartbeatTransferer<JobStateHeartbeat> {
	@Override
	public void send(JobStateHeartbeat heartbeat, OutputStream raw) throws IOException {
		DataOutputStream output = new DataOutputStream(raw);
		if (heartbeat.isUnderway) {
			output.writeBoolean(true);
			output.flush();
			output.writeUTF(heartbeat.jobId);
			output.flush();
			output.writeDouble(heartbeat.progress);
			output.flush();
			output.writeBoolean(heartbeat.isFailed);
			output.flush();
		} else {
			output.writeBoolean(false);
			output.flush();
		}	
	}

	@Override
	public JobStateHeartbeat receive(InputStream raw) throws IOException {
		DataInputStream input = new DataInputStream(raw);

		boolean isUnderway = input.readBoolean();
		if (isUnderway) {
			String jobId = input.readUTF();
			double progress = input.readDouble();
			boolean isFailed = input.readBoolean();
			return new JobStateHeartbeat(jobId, progress, isFailed);
		}else{
			return new JobStateHeartbeat();
		}
	}

}
